// =======================================================================
// 
//       Filename:  page.cpp
// 
//    Description:  
// 
//        Version:  1.0
//        Created:  27.03.2010 19:37:30
//       Revision:  none
//       Compiler:  g++
// 
//         Author:  Dominik 'domachine' Burgdörfer (-), dominik.burgdoerfer@googlemail.com
//        Company:  -
// 
// =======================================================================

#include "page.hpp"
#include "navigation/node.hpp"
#include <fstream>
#include <boost/foreach.hpp>
#include <iostream>
#define foreach BOOST_FOREACH

using namespace std;
using namespace boost::filesystem;

namespace webplodder {
    Page::Page(const path& sourcePath,
               const path& outputPath)
        : map<string,string>(), mSourcePath(sourcePath),
          mOutputPath(outputPath)
    {
    }

    void Page::parse()
    {
        ifstream in(mSourcePath.string().c_str());
        YAML::Parser parser(in);

        YAML::Node doc;

        parser.GetNextDocument(doc);
        YAML::Iterator it;

        string key;

        for(it = doc.begin(); it != doc.end(); ++it) {
            it.first() >> key;
            it.second() >> (*this)[key];
        }
    }

    void Page::installNavigation(const vector<navigation::Node>& navi)
    {
        path parentPath = mOutputPath.parent_path();

        foreach(navigation::Node node, navi) {
            path wishPath(".");
            path currentPath = node.href();
            //path cParentPath = currentPath.parent_path();
            path::iterator pPathIter = parentPath.begin();
            path::iterator cPathIter = currentPath.begin();

            while(*pPathIter == *cPathIter) {
                ++pPathIter;
                ++cPathIter;

                if(pPathIter == parentPath.end())
                    break;
            }

            while(pPathIter != parentPath.end()) {
                wishPath /= "..";
                ++pPathIter;
            }
            
            while(cPathIter != currentPath.end()) {
                wishPath /= *cPathIter;
                ++cPathIter;
            }

            mNavigation.push_back(navigation::Node(node.title(), 
                                  wishPath.string(),
                                  node.pos()));
        }
    }
    
    path Page::sourcePath() const
    {
        return mSourcePath;
    }

    path Page::outputPath() const
    {
        return mOutputPath;
    }

    vector<navigation::Node>& Page::navigation() {
        
        return mNavigation;
    }
}
